package leetcode;

/***
 * 题目：搜索插入位置
 * 链接：https://leetcode.cn/problems/search-insert-position/description/?envType=study-plan-v2&envId=top-100-liked
 * 思路：二分查找
 */
public class SearchInsert {
    public static void main(String[] args) {
        int[] nums = {1, 3, 5, 6};
        int target = 7;
        int index = searchInsert(nums, target);
        System.out.println("index = " + index);
    }
    //二分关键点，找中位数
    public static int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            int midValue = nums[mid];
            if(midValue == target){
                return mid;
            }else if(midValue < target){
                left = mid + 1;
            }else if(midValue > target){
                right = mid - 1;
            }
        }
        return left;
    }
}
